package com.sanji.sjmallmodule.phoneshell;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sanji.sjmallapp.BaseActivity;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallmodule.goods.GoodsDetailsActivity;
import com.sanji.sjmallmodule.main.MainActivity;
import com.sanji.sjmallutils.ImageUtil;
import com.sanji.sjmallutils.Tools;
import com.sanji.sjmallwidget.NumControlView;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.sanji.sjmallconfig.ConfigConts.STATUS_STRING;
import static com.sanji.sjmallconfig.ConfigConts.STATUS_SUCCESS;

/**
 * 确认订单
 * Created by ZSF on 17/9/8.
 */

public class FirmShellOrderActivity extends BaseActivity implements View.OnClickListener,NumControlView.OnNumChangeListener,NoHttpListener {

    @BindView(R.id.common_back_img)
    ImageView mCommonBackImg;
    @BindView(R.id.common_left_tv)
    TextView mCommonLeftTv;
    @BindView(R.id.firm_shell_order_user_name)
    EditText userNameEt;
    @BindView(R.id.firm_shell_order_user_phone)
    EditText userPhoneEt;
    @BindView(R.id.firm_shell_order_goods_img)
    ImageView goodsImg;
    @BindView(R.id.firm_shell_order_goods_title)
    TextView goodsTitleTv;
    @BindView(R.id.firm_shell_order_goods_price)
    TextView goodsPriceTv;
    @BindView(R.id.firm_shell_order_goods_num)NumControlView numControlView;
    @BindView(R.id.firm_shell_order_result_coust_value)
    TextView goodsCoustTv;
    @BindView(R.id.firm_shell_order_result_fare_value)
    TextView fareTv;
    @BindView(R.id.firm_shell_order_submit_btn)
    TextView submitTv;
    @BindView(R.id.firm_shell_order_coust_tv)
    TextView allCoustTv;

    private ShellGoodsBean goodsBean;
    private String kkmoveId;
    //数量
    private int quantity = 1;
    private String addCartUrl;
    private Request<JSONObject> request;
    private PopupWindow shopCarWindow;//加入购物车window
    private String uid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firm_shell_order);
        ButterKnife.bind(this);

        goodsBean = (ShellGoodsBean) getIntent().getSerializableExtra("goodsBean");
        kkmoveId = getIntent().getStringExtra("kkmoveId");
        uid = myShare.getString(ConfigConts.USER_ID,"");

        initView();
    }

    private void initView() {
        mCommonBackImg.setOnClickListener(this);
        mCommonLeftTv.setOnClickListener(this);
        mCommonLeftTv.setText("确认订单信息");
        submitTv.setOnClickListener(this);
        int imageWidth = ImageUtil.setImageWidth(mCtx, 4);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(imageWidth,imageWidth);
        goodsImg.setLayoutParams(params);
        numControlView.setGoodsParameter(Integer.MAX_VALUE,-1,1,true);
        numControlView.setOnNumChangeListener(this);

        goodsCoustTv.setText("￥" + Tools.divide(goodsBean.getMembersPrice()));
        fareTv.setText("￥0.0");
        allCoustTv.setText("￥" + Tools.divide(goodsBean.getMembersPrice()));

        goodsTitleTv.setText(goodsBean.getTitle() +" "+ goodsBean.getCategoryName());
        Glide.with(mCtx).load(goodsBean.getImageUrl())
                //使用centerCrop是利用图片图填充ImageView设置的大小，如果ImageView的Height是match_parent则图片就会被拉伸填充
                .centerCrop()
                //当加载网络图片时，由于加载过程中图片未能及时显示，此时可能需要设置等待时的图片，通过placeHolder()方法
                .placeholder(R.mipmap.default_3j_img)
                //当加载图片失败时，通过error(Drawable drawable)方法设置加载失败后的图片显示
                .error(R.mipmap.default_3j_img)
                .crossFade()
                //DiskCacheStrategy.SOURCE：缓存原始数据，DiskCacheStrategy.RESULT：缓存变换(如缩放、裁剪等)后的资源数据，
                // DiskCacheStrategy.NONE：什么都不缓存，DiskCacheStrategy.ALL：缓存SOURC和RESULT。
                // 默认采用DiskCacheStrategy.RESULT策略，对于download only操作要使用DiskCacheStrategy.SOURCE。
//                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .into(goodsImg);
        goodsPriceTv.setText("￥"+Tools.divide(goodsBean.getMembersPrice()));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back_img:
            case R.id.common_left_tv:
                finishActivity();
                break;
            case R.id.firm_shell_order_submit_btn:
                String userName = userNameEt.getText().toString().trim();
                if ("".equals(userName)){
                    Tools.toastTools(mCtx,"请输入终端客户姓名");
                    return;
                }
                String userPhone = userPhoneEt.getText().toString().trim();
                if ("".equals(userPhone)){
                    Tools.toastTools(mCtx,"请输入终端客户电话");
                    return;
                }
                addCartUrl = ConfigAPI.PHONE_SHELL_ADD_CART;
                request = NoHttp.createJsonObjectRequest(addCartUrl, RequestMethod.POST);
                request.addHeader("X-Authorization-MemberId",uid);
                try {
                    JSONObject json = new JSONObject();
                    json.put("goodsId",goodsBean.getId());
                    json.put("kkmoveId",kkmoveId);
                    json.put("quantity",quantity);
                    json.put("username",userName);
                    json.put("userMobile",userPhone);

                    request.setDefineRequestBodyForJson(json);
                    //设置取消标志
                    request.setCancelSign(addCartUrl.hashCode());
                    //发送登录请求
                    NoHttpCallBack.getInstance().add(mCtx, addCartUrl.hashCode(), request, this, true, true);

                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case R.id.continue_shop_btn:
                shopCarWindow.dismiss();
                finishActivity();
                break;
            case R.id.set_account_btn:
                shopCarWindow.dismiss();
                intent = new Intent(mCtx,ShellShopCarActivity.class);
                startActivity(intent);
                finishActivity();
                break;

        }
    }

    @Override
    public void onNumChange(View view, int num) {
        quantity = num;
        numControlView.synchroNumEt(num);

        double total = Tools.multiply(goodsBean.getMembersPrice(),num);
        allCoustTv.setText("￥" + Tools.divide(total));
        goodsCoustTv.setText("￥" + Tools.divide(total));
    }

    @Override
    public void onSuccessed(int what, Response response) {
        JSONObject object = (JSONObject) response.get();
        String status = object.optString(STATUS_STRING);
        if (what == addCartUrl.hashCode()) {
            if (status.equals(STATUS_SUCCESS)){
//                Tools.toastTools(mCtx,"提交成功");
                showShopCarWindow();
            }else{
                Tools.toastTools(mCtx,"提交失败，稍后重试");
            }
        }
    }

    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(mCtx, getString(R.string.request_false));
    }

    /**
     * 立马结算、继续购物的popWindow
     */
    public void showShopCarWindow() {
        final WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = 0.8f;
        this.getWindow().setAttributes(lp);
        if (null == shopCarWindow) {
            View view = LayoutInflater.from(this).inflate(R.layout.activity_goods_detail_pop_shop_car, null);
            view.findViewById(R.id.continue_shop_btn).setOnClickListener(this);
            view.findViewById(R.id.set_account_btn).setOnClickListener(this);
            shopCarWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            shopCarWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.colorWhite));
            shopCarWindow.setFocusable(true);
            shopCarWindow.setOutsideTouchable(true);
            shopCarWindow.setAnimationStyle(R.style.my_popwindow);
        }
        //设置popview在y上的偏移量
        int y = ImageUtil.setImageWidth(this, 1);
        shopCarWindow.showAsDropDown(mCommonLeftTv, 0, y / 2);

        shopCarWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });

    }
}
